package org.example.analysis.service;

import lombok.extern.slf4j.Slf4j;
import org.example.analysis.model.entity.JavaClassInfo;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * README文件生成器
 */
@Slf4j
public class ReadmeGenerator {
    private final TemplateEngine templateEngine;
    private static final int MAX_CLASSES = 10;
    
    public ReadmeGenerator() {
        // 初始化Thymeleaf模板引擎
        templateEngine = new TemplateEngine();
        
        // 配置模板解析器
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setTemplateMode(TemplateMode.TEXT);
        resolver.setPrefix("/templates/");
        resolver.setSuffix(".md");
        resolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resolver.setCacheable(false);
        
        templateEngine.setTemplateResolver(resolver);
    }
    
    /**
     * 生成README文件
     *
     * @param classInfoList Java类信息列表
     * @param outputFile 输出文件
     */
    public void generateReadme(List<JavaClassInfo> classInfoList, File outputFile) {
        try {
            // 按类的大小（方法数+字段数）排序并限制数量
            List<JavaClassInfo> sortedClasses = classInfoList.stream()
                    .sorted((c1, c2) -> {
                        int size1 = (c1.getMethods() != null ? c1.getMethods().size() : 0) +
                                  (c1.getFields() != null ? c1.getFields().size() : 0);
                        int size2 = (c2.getMethods() != null ? c2.getMethods().size() : 0) +
                                  (c2.getFields() != null ? c2.getFields().size() : 0);
                        return Integer.compare(size2, size1); // 降序排序
                    })
                    .limit(MAX_CLASSES)
                    .collect(Collectors.toList());
            
            // 准备模板上下文
            Context context = new Context();
            context.setVariable("classes", sortedClasses);
            context.setVariable("currentTime", new Date());
            context.setVariable("totalClasses", classInfoList.size());
            
            // 生成文档
            try (Writer writer = new OutputStreamWriter(
                    new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
                templateEngine.process("readme", context, writer);
            }
            
            log.info("README文件生成成功: {}", outputFile.getAbsolutePath());
        } catch (IOException e) {
            log.error("生成README文件失败", e);
            throw new RuntimeException("生成README文件失败", e);
        }
    }
} 